import {
  getRoutes,
  requestOrgTree2,
  requestRegionTree,
  getUser,
  getTreeByLoginOrg,
} from '@/api/global'
import { requestDictCodeList } from '@/api/roadSurface'

const global: any = {
  namespace: true,
  state: {
    routes: [],
    orgTree: [],
    userOrgTree: [],
    dictCodeList: {},
    lockPermsList: [],
    Authority: [],
    pageSize: 15,
    pageSizes: [15, 50, 100, 200],
    basePath: process.env.NODE_ENV === 'production' ? '/basedata' : '',
    menuActiveIndex: window.location.pathname,
  },
  mutations: {
    saveOrgTree(state: any, payload: any) {
      state.orgTree = payload
    },
    saveUserOrgTree(state: any, payload: any) {
      state.userOrgTree = payload
    },
    saveDictCodeList(state: any, payload: any) {
      state.dictCodeList = payload
    },
    saveLockPermsList(state: any, payload: any) {
      state.lockPermsList = payload
    },
    saveUser(state: any, payload: any) {
      state.routes = payload
    },
    saveAuthority(state: any, payload: any) {
      state.Authority = payload
    },
    savePageSize(state: any, payload: any) {
      state.pageSize = payload
    },
    saveMenuActiveIndex(state: any, payload: any) {
      state.menuActiveIndex = payload
    },
  },
  actions: {
    // 获取路由信息
    async getRouters({ commit }: any, params: never) {
      const rst = await getRoutes(params)
      commit('saveTypeList', rst.data)
    },
    // 获取角色权限
    GetUser({ commit }: any) {
      getUser().then((rst) => {
        commit('saveUser', rst.data.data.roles)
        commit('saveAuthority', rst.data.data.authority)
      })
    },
    // 获取机构树
    async getOrgTree({ commit }: any) {
      const rst = await requestOrgTree2()
      commit('saveOrgTree', rst.data.data)
    },
    // 获取字典信息
    async getDictCodeList({ commit, state }: any, payload: any) {
      const rst = await requestDictCodeList(payload)
      const data = rst.data.data
      const obj = {}
      for (const key in data) {
        obj[key] = data[key].map((item) => {
          item.value = item.itemValue
          item.label = item.itemText
          return item
        })
      }
      commit('saveDictCodeList', { ...state.dictCodeList, ...obj })
    },
    // 获取行政区域树
    async getRegionTree({ commit }: any, payload: any) {
      const rst = await requestRegionTree(payload)
      if (rst?.data && rst?.data?.code === 200) {
        rst.data.data.children = rst.data.data.children.map((item) => {
          item.leaf = item.regionLevel === 3
          return item
        })
        return rst.data.data
      }
    },
    // 人员信息左侧机构树
    async getUserOrgTree({ commit }: any) {
      const rst = await getTreeByLoginOrg()
      commit('saveUserOrgTree', [rst.data.data])
    },
  },
}

export default global
